//ServletConfigTest.java
package com.ylaihui.servlet;

import sun.security.krb5.Config;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//public class ServletConfigTest extends HttpServlet {
//
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
//
//        ServletConfig servletConfig = getServletConfig();
//        String username = servletConfig.getInitParameter("username");
//        System.out.println(username);
//    }
//
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
//    }
//}

public class ServletConfigTest implements Servlet{

    ServletConfig config;

    @Override
    public void init(ServletConfig config) throws ServletException {

        this.config = config;  //  这里的操作与 HttpServlet 类似
        // 获取 web.xml 中 配置的 servlet-name 的值
        String servletName = config.getServletName();
        System.out.println(servletName);  // ServletConfigTest

        // 获取 web.xml 中 <init-param> 配置的 value 的值
        String username = config.getInitParameter("username");
        System.out.println(username);  // ylaihui

        //获取 Servlet 上下文 对象 ServletContext
        ServletContext servletContext = config.getServletContext();
        System.out.println(servletContext);  // org.apache.catalina.core.ApplicationContextFacade@78802ad1

    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

        // init 方法中保存了config， 这里可以使用 config ，否则会报空指针异常
        ServletConfig servletConfig = getServletConfig();
        String username = servletConfig.getInitParameter("username");
        System.out.println("in service method:" + username);
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}


